package com.shimao.celnet.payment.controller.apitlreturn;

import com.shimao.celnet.payment.form.PPayForm;
import com.shimao.celnet.payment.model.PPay;
import com.shimao.celnet.payment.model.PPayDetail;
import com.shimao.celnet.payment.model.response.NotifyDetails;
import com.shimao.celnet.payment.model.response.NotifyPay;
import com.shimao.celnet.payment.service.IAppInterfaceService;
import com.shimao.celnet.payment.service.PPayService;
import com.shimao.celnet.payment.service.apiservice.AsyncNotifyService;
import com.shimao.celnet.payment.util.FinalUtil;
import com.shimao.celnet.payment.util.MyDateUtil;
import com.shimao.celnet.payment.util.SignCheckUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;

/**
 * 接受通联回调通知的接口，在支付成功后，通联根据我们传入的notifyURL回调
 * 通联--->支付平台
 * 2019/5/10
 * Matt
 */
@RestController
@RequestMapping(value = "/tlPay")
public class CallIn_AllinOutPayRetInfoInController {
    //支付订单Service
    @Autowired
    private PPayService pPayService;

    @Autowired
    private AsyncNotifyService notifyService;

    @Autowired//接口应用注册Service
    private IAppInterfaceService iAppInterfaceService;

    @RequestMapping(value = "/return", method = RequestMethod.POST)
    public String outPayRetInfoOut(HttpServletRequest request) throws IOException {
        System.out.println(".................>>>>>>>Matt通联通知接口");
        PPayForm pPayFormResult;
        //动态遍历获取所有收到的参数,此步非常关键,因为收银宝以后可能会加字段,动态获取可以兼容
        TreeMap<String, String> params = getParams(request);
        pPayFormResult = pPayService.getInfoBytrxid(params.get("trxid"));
        //如果支付状态为已支付则直接返回
        if(FinalUtil.ALLIN_SUCCESS_CODE.equals(pPayFormResult.getPayStatus())){
            //收到通知,返回success
            return "success";
        }
        /**
         * 更新订单表的订单状态
         */
        PPay pPay = new PPay();
        pPay.setGuid(pPayFormResult.getGuid());//账单guid
        pPay.setPayStatus(FinalUtil.ALLIN_SUCCESS_CODE);//支付状态
        pPay.setPayEndTime(String.valueOf(MyDateUtil.StrToDate(params.get("paytime"),MyDateUtil.format_yyyyMMddHHmmss).getTime()));//支付完成时间
        pPayService.update(pPay);
        PPayForm pPayFormResultAfterUD = pPayService.getInfoBytrxid(params.get("trxid"));
        PPayDetail d = pPayFormResult.getPayDetailList().get(0);
        NotifyPay pay = new NotifyPay();
        NotifyDetails detalis = new NotifyDetails();
        List<NotifyDetails> detailsList = new ArrayList<>();
        detalis.setbRemark(d.getRemark());
        detalis.setReceivableId(d.getExsysDetailId());
        detalis.setTotalReceivableAmount(d.getAmount());
        detailsList.add(detalis);
        pay.setPaymentId(pPayFormResultAfterUD.getGuid());
        pay.setPayAmount(pPayFormResultAfterUD.getPayAmount());
        pay.setPayStartTime(pPayFormResultAfterUD.getPayStartTime().substring(0,19));
        pay.setPayType(pPayFormResultAfterUD.getPayType());
        pay.setUserId(pPayFormResultAfterUD.getPayUserSfGuid());
        pay.setUserName(pPayFormResultAfterUD.getPayUserName());
        pay.setPayEndTime(pPayFormResultAfterUD.getPayEndTime().substring(0,19));
        pay.setTrxId(pPayFormResultAfterUD.getTrxid());
        pay.setPayStatus(pPayFormResultAfterUD.getPayStatus());
        pay.setPaymentList(detailsList);
        Map<String, String> pMap = new HashMap<String, String>();
        //获取签名
        //获取token
        //应用ID
        pMap.put("appKey", pPayFormResultAfterUD.getAppKey());
        //接口ID
        pMap.put("interfaceId", pPayFormResultAfterUD.getInterfaceId());
        String signToken = iAppInterfaceService.getAppToken(pMap);
        //生成签名
        TreeMap<String, String> headers = new TreeMap<String, String>();
        headers.put(FinalUtil.SIGN_PAYMENT_ID, pay.getPaymentId());
        headers.put(FinalUtil.SIGN_TRXAMT, pay.getPayAmount());
        try {
            pay.setSign(SignCheckUtil.getMySign(headers,signToken).toUpperCase());
        } catch (Exception e) {
            System.out.println(e.getMessage()+e.getStackTrace());
        }
        //开启异步通知方法
        notifyService.notifyTLCust(pay,pPayFormResult.getGoBackUrl());
        return "success";
    }
    /**
     * 动态遍历获取request的参数
     *
     * @param request
     * @return
     * @throws IOException
     */
    private TreeMap<String, String> getParams(HttpServletRequest request) throws IOException {
        request.setCharacterEncoding("utf-8");
        TreeMap<String, String> map = new TreeMap<String, String>();
        Map reqMap = request.getParameterMap();
        for (Object key : reqMap.keySet()) {
            String value = ((String[]) reqMap.get(key))[0];
            System.out.println("-------打印输出--------" + key + ":" + value);
            map.put(key.toString(), value);
        }
        return map;
    }
}